package com.whlilong.jxc.filemanager.editor;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.IJobChangeEvent;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.core.runtime.jobs.JobChangeAdapter;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TableLayout;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;

import com.whlilong.jxc.db.DbManager;
import com.whlilong.jxc.dialog.ClientInfoSearchByConditon;
import com.whlilong.jxc.editor.support.ClientInfoEditorSupport;
import com.whlilong.jxc.listener.IEditorListener;
import com.whlilong.jxc.model.Keshang;
import com.whlilong.jxc.model.Khinfo;
import com.whlilong.jxc.model.Kstype;
import com.whlilong.jxc.print.IconSource;
import com.whlilong.jxc.print.PDocument;
import com.whlilong.jxc.print.PHLine;
import com.whlilong.jxc.print.PTableBoxProvider;
import com.whlilong.jxc.print.PTextBox;
import com.whlilong.jxc.print.PVSpace;
import com.whlilong.jxc.print.PrintPreview;
import com.whlilong.jxc.print.SWTPTable;
import com.whlilong.jxc.service.editor.IEditorService;
import com.whlilong.jxc.sys.CnToSpellFirstChar;
import com.whlilong.jxc.sys.ExtentionInfo;
import com.whlilong.jxc.sys.SetTableColColorListener;
import com.whlilong.jxc.treemodel.KeshangTreeChildren;
import com.whlilong.jxc.treemodel.KeshangTreeParent;
import com.whlilong.jxc.treemodel.MerchantTypeTreeChildren;
import com.whlilong.jxc.treemodel.MerchantTypeTreeParent;
import com.whlilong.jxc.ui.provider.ClientInfoContentProvider;
import com.whlilong.jxc.ui.provider.ClientInfoLableProvider;
import com.whlilong.jxc.ui.provider.DistrictTreeContentProvider;
import com.whlilong.jxc.ui.provider.DistrictTreeLabelProvider;
import com.whlilong.jxc.ui.provider.MerchantTypeTreeContentProvider;
import com.whlilong.jxc.ui.provider.MerchantTypeTreeLabelProvider;
import com.whlilong.jxc.ui.sorter.ClientInfoSorter;

/**
 * 客户信息编辑器
 * 
 * @author sjy
 * 
 */
public class ClientInfoEditor extends AbstractEditor implements IEditorService, IEditorListener {

	protected List<Khinfo> list = new ArrayList<Khinfo>();
	protected List<Keshang> districtList = new ArrayList<Keshang>();
	protected ExtentionInfo extentionInfo = null;
	private Label infoLabel;
	private Table table;
	private String khid;
	private String khName;
	private Text khbh;
	private Text khname;
	private Combo combo;
	private Label khbhLabel;
	private Label khnameLabel;
	private Button findBt;
	private TableLayout tableLayout;
	private int i = 0;
	protected int selItem;
	protected Text text;
	protected Combo tableCombo;
	private Label pymLabel;
	private Text pymText;
	private Label yzbmLabel;
	private Text yzbm;
	private Label khqyLabel;
	private Combo khqy;
	private Label khtpLabel;
	private Combo khtp;
	private Label telLabel;
	private Text tel;
	private Label addrLabel;
	private Text addr;
	private Label lxrLabel;
	private Text lxr;
	private Label faxLabel;
	private Text fax;
	private Label mailLabel;
	private Text mail;
	private Label yhLabel;
	private Text yh;
	private Shell shell;
	private Button add;
	private boolean isSave = true;

	public ClientInfoEditor() {
		// TODO Auto-generated constructor stub
	}

	protected Control createGroupText(Composite parent) {
		// TODO Auto-generated method stub
		Composite container = new Composite(parent, SWT.NONE);
		final GridLayout gl = new GridLayout(2, false);
		container.setLayout(gl);
		GridData gd = new GridData(GridData.FILL_HORIZONTAL);
		combo = new Combo(container, SWT.READ_ONLY);
		combo.add("1--区域");
		combo.add("2--类别");
		combo.select(0);
		combo.setLayoutData(gd);
		createTableViewer(container);
		addComboListener();
		createTreeViewer(container);

		return container;
	}

	@SuppressWarnings("unchecked")
	private void createTableViewer(Composite parent) {
		// TODO Auto-generated method stub
		GridData gd = new GridData(GridData.FILL_BOTH);
		gd.verticalSpan = 2;
		Composite composite = new Composite(parent, SWT.NONE);
		GridLayout gl = new GridLayout(8, false);
		composite.setLayout(gl);
		composite.setLayoutData(gd);

		// 第一行
		infoLabel = new Label(composite, SWT.NONE);
		gd = new GridData(GridData.FILL_HORIZONTAL);
		gd.heightHint = 20;
		gd.horizontalSpan = 8;
		infoLabel.setLayoutData(gd);

		gd = new GridData();
		gd.widthHint = 90;
		gd.verticalIndent = 10;
		gd.heightHint = 20;
		// 第二行
		khbhLabel = new Label(composite, SWT.RIGHT);
		khbhLabel.setText("客户编号：");
		khbhLabel.setLayoutData(gd);
		khbh = new Text(composite, SWT.BORDER);
		khbh.setLayoutData(gd);
		khbh.setTextLimit(20);

		khnameLabel = new Label(composite, SWT.RIGHT);
		khnameLabel.setText("客户名称：");
		khnameLabel.setLayoutData(gd);
		khname = new Text(composite, SWT.BORDER);
		khname.setLayoutData(gd);
		khname.addModifyListener(new ModifyListener() {

			@SuppressWarnings("static-access")
			@Override
			public void modifyText(ModifyEvent e) {
				// TODO Auto-generated method stub
				CnToSpellFirstChar c = new CnToSpellFirstChar();
				String py = c.makePy(khname.getText());
				pymText.setText(py.substring(0, py.length() - 1).toUpperCase());
				pymText.selectAll();
			}

		});

		pymLabel = new Label(composite, SWT.RIGHT);
		pymLabel.setText("拼音码：");
		pymLabel.setLayoutData(gd);
		pymText = new Text(composite, SWT.BORDER);
		pymText.setLayoutData(gd);

		yzbmLabel = new Label(composite, SWT.RIGHT);
		yzbmLabel.setText("邮政编码：");
		yzbmLabel.setLayoutData(gd);
		yzbm = new Text(composite, SWT.BORDER);
		yzbm.setLayoutData(gd);

		// 第三行
		khqyLabel = new Label(composite, SWT.RIGHT);
		khqyLabel.setText("客户区域：");
		khqyLabel.setLayoutData(gd);

		khqy = new Combo(composite, SWT.READ_ONLY);
		khqy.add("不定");
		districtList = extentionInfo.getInstance().getKeshanginfo();
		for (int k = 0; k < districtList.size(); k++) {
			Keshang ksarea = (Keshang) districtList.get(k);
			khqy.add(ksarea.getKeshangarea());
		}

		khqy.select(0);
		khqy.setLayoutData(gd);

		khtpLabel = new Label(composite, SWT.RIGHT);
		khtpLabel.setText("客户类别：");
		khtpLabel.setLayoutData(gd);
		khtp = new Combo(composite, SWT.READ_ONLY);
		khtp.add("不定");
		List kstplist = extentionInfo.getInstance().getKstypeinfo();
		for (int k = 0; k < kstplist.size(); k++) {
			Kstype kstype = (Kstype) kstplist.get(k);
			khtp.add(kstype.getKstype());
		}
		khtp.select(0);
		khtp.setLayoutData(gd);

		telLabel = new Label(composite, SWT.RIGHT);
		telLabel.setText("客户电话：");
		telLabel.setLayoutData(gd);
		tel = new Text(composite, SWT.BORDER);
		tel.setLayoutData(gd);

		addrLabel = new Label(composite, SWT.RIGHT);
		addrLabel.setText("客户地址：");
		addrLabel.setLayoutData(gd);
		addr = new Text(composite, SWT.BORDER);
		addr.setLayoutData(gd);

		// 第四行
		lxrLabel = new Label(composite, SWT.RIGHT);
		lxrLabel.setText("联系人：");
		lxrLabel.setLayoutData(gd);
		lxr = new Text(composite, SWT.BORDER);
		lxr.setLayoutData(gd);

		faxLabel = new Label(composite, SWT.RIGHT);
		faxLabel.setText("传真：");
		faxLabel.setLayoutData(gd);
		fax = new Text(composite, SWT.BORDER);
		fax.setLayoutData(gd);

		mailLabel = new Label(composite, SWT.RIGHT);
		mailLabel.setText("E-Mail：");
		mailLabel.setLayoutData(gd);
		mail = new Text(composite, SWT.BORDER);
		mail.setLayoutData(gd);

		yhLabel = new Label(composite, SWT.RIGHT);
		yhLabel.setText("银行账号：");
		yhLabel.setLayoutData(gd);
		yh = new Text(composite, SWT.BORDER);
		yh.setLayoutData(gd);

		gd = new GridData();
		gd.widthHint = 100;
		gd.verticalIndent = 10;
		findBt = new Button(composite, SWT.NONE);
		findBt.setText("查询F7");

		findBt.setLayoutData(gd);
		findBt.addMouseListener(new MouseAdapter() {

			@Override
			public void mouseDown(MouseEvent e) {
				// TODO Auto-generated method stub
				search();
			}

		});

		add = new Button(composite, SWT.NONE);
		add.setText("添加F10");
		add.setLayoutData(gd);
		add.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				addInfo();
			}
		});

		tableViewer = new TableViewer(composite, SWT.BORDER | SWT.H_SCROLL
				| SWT.FULL_SELECTION);
		tableViewer.setUseHashlookup(true);

		gd = new GridData(GridData.FILL_BOTH);
		gd.horizontalSpan = 8;
		table = tableViewer.getTable();
		table.setLayoutData(gd);
		table.setLayout(tableLayout);
		table.setToolTipText("点击单元格对数据进行修改！");
		// 设置行高
		table.addListener(SWT.MeasureItem, new Listener() {
			public void handleEvent(Event event) {
				event.height = 20;
			}
		});
		
		ClientInfoEditorSupport editingSupport = new ClientInfoEditorSupport(
				tableViewer, 1, this);
		createColumn("ID", ClientInfoSorter.ID_ASC,
				ClientInfoSorter.ID_DESC, editingSupport);
		editingSupport = new ClientInfoEditorSupport(tableViewer, 2, this);
		createColumn("客户编号", ClientInfoSorter.ID_ASC,
				ClientInfoSorter.ID_DESC, editingSupport);
		manager.addITextKeyChangeListener(editingSupport);
		
		editingSupport = new ClientInfoEditorSupport(tableViewer, 3, this);
		createColumn("客户名称", ClientInfoSorter.ID_ASC,
				ClientInfoSorter.ID_DESC, editingSupport);
		manager.addITextKeyChangeListener(editingSupport);
		
		editingSupport = new ClientInfoEditorSupport(tableViewer, 4, this);
		createColumn("拼音码", ClientInfoSorter.ID_ASC,
				ClientInfoSorter.ID_DESC, editingSupport);
		manager.addITextKeyChangeListener(editingSupport);
		
		editingSupport = new ClientInfoEditorSupport(tableViewer, 5, this);
		createColumn("客户区域名称", null, null, editingSupport);
		manager.addITextKeyChangeListener(editingSupport);
		
		editingSupport = new ClientInfoEditorSupport(tableViewer, 6, this);
		createColumn("客户类别名称", null, null, editingSupport);
		manager.addITextKeyChangeListener(editingSupport);
		
		editingSupport = new ClientInfoEditorSupport(tableViewer, 7, this);
		createColumn("客户联系电话", null, null, editingSupport);
		manager.addITextKeyChangeListener(editingSupport);
		
		editingSupport = new ClientInfoEditorSupport(tableViewer, 8, this);
		createColumn("客户地址", null, null, editingSupport);
		manager.addITextKeyChangeListener(editingSupport);
		
		editingSupport = new ClientInfoEditorSupport(tableViewer, 9, this);
		createColumn("联系人", null, null, editingSupport);
		manager.addITextKeyChangeListener(editingSupport);
		
		editingSupport = new ClientInfoEditorSupport(tableViewer, 10, this);
		createColumn("传真", null, null, editingSupport);
		manager.addITextKeyChangeListener(editingSupport);
		
		editingSupport = new ClientInfoEditorSupport(tableViewer, 11, this);
		createColumn("邮政编码", null, null, editingSupport);
		manager.addITextKeyChangeListener(editingSupport);
		
		editingSupport = new ClientInfoEditorSupport(tableViewer, 12, this);
		createColumn("电子邮箱", null, null, editingSupport);
		manager.addITextKeyChangeListener(editingSupport);
		
		editingSupport = new ClientInfoEditorSupport(tableViewer, 13, this);
		createColumn("银行账号", null, null, editingSupport);
		manager.addITextKeyChangeListener(editingSupport);

		table.setHeaderVisible(true);
		table.setLinesVisible(true);

		initial();
		// initial the tabelViewer
		tableViewer.setContentProvider(new ClientInfoContentProvider());
		tableViewer.setLabelProvider(new ClientInfoLableProvider());

		tableViewer.setInput(list);

		table.addListener(SWT.EraseItem, new SetTableColColorListener(table));


		table.select(0);
		table.setFocus();

	}

	public void addInfo() {
		// TODO Auto-generated method stub
		Khinfo kh = new Khinfo();
		String khbhid = khbh.getText();
		String khName = khname.getText();
		boolean flag = true;// id ,name 是否重复
		if (!khbhid.equals("") && !khName.equals("")) {
			for (int i = 0; i < list.size(); i++) {
				if (list.get(i).getKhid().equals(khbhid)) {
					flag = false;
					MessageDialog.openInformation(null, "错误", "客户编号已存在！");
					break;
				}
				if (list.get(i).getKhname().equals(khName)) {
					flag = false;
					MessageDialog.openInformation(null, "错误", "客户名称已存在！");
					break;
				}

			}
			if (flag) {
				kh.setKhid(khbhid);
				kh.setKhname(khName);
				kh.setKhareaname(khqy.getText());
				kh.setKhtpname(khtp.getText());
				kh.setKhtel(tel.getText());
				kh.setKhaddress(addr.getText());
				kh.setFax(fax.getText());
				kh.setMail(mail.getText());
				kh.setPeople(lxr.getText());
				kh.setPym(pymText.getText());
				kh.setYh(yh.getText());
				kh.setYzbm(yzbm.getText());
				DbManager.getInstance().insert(kh);
				refresh();
			}
		} else {
			MessageDialog.openInformation(null, "错误", "客户编号或客户名称为空！");
		}
	}

	private void createTreeViewer(Composite parent) {
		// TODO Auto-generated method stub
		treeViewer = new TreeViewer(parent, SWT.BORDER | SWT.V_SCROLL
				| SWT.FULL_SELECTION);
		treeViewer.setUseHashlookup(true);

		GridData gd = new GridData();
		gd.verticalAlignment = SWT.TOP;
		// gd.verticalSpan = 3;
		final Tree tree = treeViewer.getTree();
		tree.setLayoutData(new GridData(GridData.FILL_VERTICAL));
		final TreeColumn category = new TreeColumn(tree, SWT.LEFT);
		category.setWidth(100);
		category.setText("客户地区");
		treeViewer.setContentProvider(new DistrictTreeContentProvider());
		treeViewer.setLabelProvider(new DistrictTreeLabelProvider());
		treeViewer.setInput(extentionInfo.getInstance().getKeshang());

		tree.setHeaderVisible(true);
		tree.setLinesVisible(true);

		treeViewer.expandToLevel(2);

		treeViewer.addSelectionChangedListener(new ISelectionChangedListener() {

			@Override
			public void selectionChanged(SelectionChangedEvent event) {
				// TODO Auto-generated method stub
				IStructuredSelection selection = (IStructuredSelection) event
						.getSelection();
				if (selection.getFirstElement() instanceof KeshangTreeChildren) {
					KeshangTreeChildren ktc = (KeshangTreeChildren) selection
							.getFirstElement();
					String area = ktc.getKeshang().getKeshangarea();
					tableViewer.getTable().clearAll();
					tableViewer.setInput(getKhAreaTpinfo(area, null));
				}
				if (selection.getFirstElement() instanceof KeshangTreeParent) {
					initial();
					tableViewer.getTable().clearAll();
					tableViewer.setInput(list);
				}
				if (selection.getFirstElement() instanceof MerchantTypeTreeChildren) {
					MerchantTypeTreeChildren ktc = (MerchantTypeTreeChildren) selection
							.getFirstElement();
					String type = ktc.getKstype().getKstype();
					tableViewer.getTable().clearAll();
					tableViewer.setInput(getKhAreaTpinfo(null, type));
				}
				if (selection.getFirstElement() instanceof MerchantTypeTreeParent) {
					initial();
					tableViewer.getTable().clearAll();
					tableViewer.setInput(list);
				}

			}

		});

	}

	private void addComboListener() {
		// TODO Auto-generated method stub
		combo.addSelectionListener(new SelectionListener() {

			@Override
			public void widgetDefaultSelected(SelectionEvent e) {
				// TODO Auto-generated method stub

			}

			@Override
			public void widgetSelected(SelectionEvent e) {
				// TODO Auto-generated method stub
				i = combo.getSelectionIndex();
				if (i == 0) {
					treeViewer.getTree().getColumn(0).setText("客户地区");
					treeViewer
							.setContentProvider(new DistrictTreeContentProvider());
					treeViewer
							.setLabelProvider(new DistrictTreeLabelProvider());
					treeViewer.setInput(extentionInfo.getInstance()
							.getKeshang());

					treeViewer.expandToLevel(2);
				}
				if (i == 1) {
					treeViewer.getTree().getColumn(0).setText("客户类别");
					treeViewer
							.setContentProvider(new MerchantTypeTreeContentProvider());
					treeViewer
							.setLabelProvider(new MerchantTypeTreeLabelProvider());
					treeViewer
							.setInput(extentionInfo.getInstance().getKstype());

					treeViewer.expandToLevel(2);
				}
			}

		});
	}

	public void print() {
		// TODO Auto-generated method stub
		final PDocument doc = new PDocument("print");

		PTextBox t;

		t = new PTextBox(doc);

		t.setText("武汉立隆客商信息");

		new PVSpace(doc, 0.5);
		new PHLine(doc, 0.02, SWT.COLOR_RED);
		new PVSpace(doc, 0.5);

		// create the table
		SWTPTable swttable = new SWTPTable(doc);
		swttable.setTable(table);
		swttable.setBoxProvider(new PTableBoxProvider());
		
		PrintPreview pr = new PrintPreview(null, "信息打印", IconSource
				.getImage("print"), doc);
		pr.onPrint();
	}

	public void save() {
		// TODO Auto-generated method stub
		if(!isSave){
			MessageDialog.openWarning(null, "提示", "数据不能保存！");
			return;
		}
		manager.notifyListener();
		Iterator data = list.iterator();
		if (!data.hasNext()) {
			MessageDialog.openWarning(null, "提示", "没有需要保存的数据！");
			return;
		}

		Job job = new Job("正在保存数据。。。") {

			@SuppressWarnings("unchecked")
			@Override
			protected IStatus run(IProgressMonitor monitor) {
				// TODO Auto-generated method stub
				monitor.beginTask("正在保存数据。。。", IProgressMonitor.UNKNOWN);
				for (int i = 0; i < list.size(); i++) {
					Khinfo khinfo = (Khinfo) list.get(i);
					int id = khinfo.getId();
					int[] idBuffer = { 0 };
					Object[] idObject = { id };
					List result = (List) DbManager.getInstance().search(
							"com.whlilong.jxc.ui.khinfo.getid", idBuffer,
							idObject);
					CnToSpellFirstChar c = new CnToSpellFirstChar();
					String pym = "";
					if (result.size() > 0) {
						String khname = khinfo.getKhname();
						String khid = khinfo.getKhid();
						if (khid != null && !khid.equals("") && khname != null
								&& !khname.equals("")) {
							int count = 0;
							Khinfo k = (Khinfo) result.get(0);
							pym = c.makePy(khname);
							k.setKhid(khid);
							k.setKhname(khinfo.getKhname());
							k.setFax(khinfo.getFax());
							k.setKhaddress(khinfo.getKhaddress());
							k.setKhareaname(khinfo.getKhareaname());
							k.setKhtel(khinfo.getKhtel());
							k.setKhtpname(khinfo.getKhtpname());
							k.setMail(khinfo.getMail());
							k.setPeople(khinfo.getPeople());
							k.setPym(pym.substring(0, pym.length()-1).toUpperCase());
							k.setYh(khinfo.getYh());
							k.setYzbm(khinfo.getYzbm());
							monitor.worked(1);
							DbManager.getInstance().update(k);
						} else {
							return Status.CANCEL_STATUS;
						}

					} else {
						String khname = khinfo.getKhname();
						String khid = khinfo.getKhid();
						if (khid != null && !khid.equals("") && khname != null
								&& !khname.equals("")) {
							Khinfo ks = new Khinfo();
							pym = c.makePy(khname);
							ks.setKhid(khid);
							ks.setKhname(khinfo.getKhname());
							ks.setFax(khinfo.getFax());
							ks.setKhaddress(khinfo.getKhaddress());
							ks.setKhareaname(khinfo.getKhareaname());
							ks.setKhtel(khinfo.getKhtel());
							ks.setKhtpname(khinfo.getKhtpname());
							ks.setMail(khinfo.getMail());
							ks.setPeople(khinfo.getPeople());
							ks.setPym(pym.substring(0, pym.length()-1).toUpperCase());
							ks.setYh(khinfo.getYh());
							ks.setYzbm(khinfo.getYzbm());
							DbManager.getInstance().insert(ks);
						} else {

							return Status.CANCEL_STATUS;
						}

					}
					list.get(i).setPym(pym.substring(0, pym.length()-1).toUpperCase());
				}
				monitor.done();
				return Status.OK_STATUS;
			}

		};
		job.addJobChangeListener(new JobChangeAdapter() {
			public void done(IJobChangeEvent event) {
				final boolean isSuccess = event.getResult().isOK();
				Display.getDefault().asyncExec(new Runnable() {
					public void run() {
						if (isSuccess) {

							MessageDialog.openInformation(null, "提示",
									"数据已经成功保存！");
							tableViewer.setInput(list);

						} else
							MessageDialog.openError(null, "错误", "编号或名称为空，数据保存失败！");
					}
				});
			}
		});
		job.setUser(false);
		job.setPriority(Job.SHORT);
		job.schedule();
	}

	@SuppressWarnings("unchecked")
	private void initial() {
		// TODO Auto-generated method stub
		khbh.setText("");
		khname.setText("");
		pymText.setText("");
		yzbm.setText("");
		khqy.select(0);
		khtp.select(0);
		tel.setText("");
		addr.setText("");
		fax.setText("");
		lxr.setText("");
		mail.setText("");
		yh.setText("");
		infoLabel.setForeground(Display.getCurrent().getSystemColor(
				SWT.COLOR_BLUE));
		infoLabel.setText("添加，删除，查询相关数据。。。");
		list = getKhinfo(null, null);
	}

	@SuppressWarnings("static-access")
	public void refresh() {
		// TODO Auto-generated method stub
		initial();
		combo.select(0);
		treeViewer.getTree().getColumn(0).setText("客户地区");
		treeViewer.setContentProvider(new DistrictTreeContentProvider());
		treeViewer.setLabelProvider(new DistrictTreeLabelProvider());
		treeViewer.setInput(extentionInfo.getInstance().getKeshang());
		treeViewer.expandToLevel(2);
		tableViewer.setInput(list);
	}

	public void create() {
		// TODO Auto-generated method stub
		infoLabel.setForeground(Display.getCurrent().getSystemColor(
				SWT.COLOR_BLUE));
		infoLabel.setText("提示：请点击参数单元格来添加修改数据，输入完成后点击保存！");
		list = getKhinfo(null, null);
		List tableList = (List) tableViewer.getInput();
		Khinfo hs = new Khinfo();
		Khinfo h = new Khinfo();
		if (list.size() == 0 && tableList.size()==0) {
			hs.setId(1);
			hs.setFax("");
			hs.setKhaddress("");
			hs.setKhareaname("不定");
			hs.setKhtpname("不定");
			hs.setKhid("");
			hs.setKhname("");
			hs.setPeople("");
			hs.setKhtel("");
			hs.setYzbm("");
			hs.setMail("");
			hs.setYh("");
			hs.setPym("");

			tableViewer.add(hs);
			list.add(hs);
			tableList.add(hs);
			int t = tableViewer.getTable().getItemCount();
			tableViewer.getTable().setSelection(t - 1);
		} else {
			h = (Khinfo) tableList.get(tableList.size() - 1);
			if (h.getKhid() == null || h.getKhid().equals("")
					|| h.getKhname() == null || h.getKhname().equals("")) {
				infoLabel.setForeground(Display.getCurrent().getSystemColor(
						SWT.COLOR_RED));
				infoLabel.setText("警告：请输入完整数据再进行添加！");
			} else {
				int id = h.getId();
				hs.setId(id + 1);
				hs.setKhid("");
				hs.setKhname("");
				hs.setKhareaname("不定");
				hs.setKhtpname("不定");
				hs.setKhtel("");
				hs.setKhaddress("");
				hs.setPeople("");
				hs.setFax("");
				hs.setYzbm("");
				hs.setMail("");
				hs.setYh("");
				hs.setPym("");

				tableViewer.add(hs);
				list.add(hs);
				tableList.add(hs);
				int t = tableViewer.getTable().getItemCount();
				for (int i = 0; i < t; i++) {
					if (((Khinfo) table.getItem(i).getData()).getId() == id + 1) {
						table.select(i);
					}
				}
			}
		}
	}

	public void delete() {
		// TODO Auto-generated method stub
		IStructuredSelection selection = (IStructuredSelection) tableViewer
				.getSelection();
		Khinfo ks = (Khinfo) selection.getFirstElement();
		if (!selection.isEmpty()) {
			if (MessageDialog.openConfirm(null, "提示", "你确定删除数据吗？")) {
				delete(ks);
			}
		} else {
			MessageDialog.openConfirm(null, "提示", "请从表格中选择一行数据进行删除！");
		}
	}

	private void delete(Khinfo clientInfo) {
		// TODO Auto-generated method stub
		String id = clientInfo.getKhid();
		if (!id.isEmpty()) {
			int[] idBuffer = { 0 };
			Object[] idObject = { id };
			List result = (List) DbManager.getInstance().search(
					"com.whlilong.jxc.ui.getkhid", idBuffer, idObject);
			Khinfo khInfo = (Khinfo) result.get(0);
			DbManager.getInstance().delete(khInfo);
		}
		refresh();
	}

	public void search() {
		// TODO Auto-generated method stub
		khid = khbh.getText();
		khName = khname.getText();
		find(khid, khName);

	}

	private void find(String id, String name) {
		// TODO Auto-generated method stub
		if ((id == null || id.equals("")) && (name == null || name.equals(""))) {
			tableViewer.setInput(getKhinfo(null, null));
		} else if ((id != null || !id.equals(""))
				&& (name == null || name.equals(""))) {
			tableViewer.setInput(getKhinfo(id, null));
		} else if ((id == null || id.equals(""))
				&& (name != null || !name.equals(""))) {
			tableViewer.setInput(getKhinfo(null, name));
		} else {
			tableViewer.setInput(getKhinfo(id, name));
		}
	}

	@SuppressWarnings("unchecked")
	private List getKhAreaTpinfo(String area, String type) {
		// TODO Auto-generated method stub
		List<Khinfo> newlist = new ArrayList<Khinfo>();
		int[] idBuffer = { 0 };
		Object[] areaObject = { area };
		Object[] typeObject = { type };
		if (area != null && type == null) {
			newlist = (List) DbManager.getInstance().search(
					"com.whlilong.jxc.ui.getkharea", idBuffer, areaObject);
		}
		if (area == null && type != null) {
			newlist = (List) DbManager.getInstance().search(
					"com.whlilong.jxc.ui.getkhtype", idBuffer, typeObject);
		}
		return list=newlist;
	}

	@SuppressWarnings("unchecked")
	private List getKhinfo(String id, String name) {
		// TODO Auto-generated method stub
		List<Khinfo> newlist = new ArrayList<Khinfo>();
		int[] idBuffer = { 0 };
		int[] idBuffer2 = { 0, 1 };
		Object[] idObject = { id };
		Object[] nameObject = { name };
		Object[] object = { id, name };
		if (id == null && name == null) {
			newlist = (List) DbManager.getInstance().search(
					"com.whlilong.jxc.ui.getkh");
		} else if (id != null && name == null) {
			newlist = (List) DbManager.getInstance().search(
					"com.whlilong.jxc.ui.getkhid", idBuffer, idObject);
		} else if (id == null && name != null) {
			newlist = (List) DbManager.getInstance().search(
					"com.whlilong.jxc.ui.getkhname", idBuffer, nameObject);
		} else {
			newlist = (List) DbManager.getInstance().search(
					"com.whlilong.jxc.ui.getkhinfo", idBuffer2, object);
		}
		return list=newlist;
	}

	@Override
	public void setFocus() {
		// TODO Auto-generated method stub

	}

	@Override
	public void searchByCondition() {
		// TODO Auto-generated method stub
		// 创建对话框样式的子shell
		Shell subshell = new Shell(shell, SWT.DIALOG_TRIM);
		ClientInfoSearchByConditon sb = new ClientInfoSearchByConditon(subshell);
		sb.open();
		if (!sb.isCacel()) {
			list = sb.getList();
			tableViewer.setInput(list);
		}
	}


	@Override
	public List getList() {
		// TODO Auto-generated method stub
		return this.list;
	}

	@Override
	public void noticeFault(String message) {
		infoLabel.setForeground(Display.getCurrent().getSystemColor(
				SWT.COLOR_RED));
		infoLabel.setText(message);
		this.isSave   = false;
		
	}

	@Override
	public void noticeSuccess() {
		infoLabel.setText("");
		this.isSave = true;		
	}

	@Override
	public void preprint() {
		// TODO Auto-generated method stub
		final PDocument doc = new PDocument("print");

		PTextBox t;

		t = new PTextBox(doc);

		t.setText("武汉立隆客商信息");

		new PVSpace(doc, 0.5);
		new PHLine(doc, 0.02, SWT.COLOR_RED);
		new PVSpace(doc, 0.5);

		// create the table
		SWTPTable swttable = new SWTPTable(doc);
		swttable.setTable(table);
		swttable.setBoxProvider(new PTableBoxProvider());
		
		PrintPreview pr = new PrintPreview(null, "信息打印", IconSource
				.getImage("print"), doc);
		pr.open();
	}

}
